package com.fingard.dsp.bank.directbank.hzcb01;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class HZCB01Transaction extends HZCB01Base implements ITransaction {

    //采用流处理方式
    //1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用writeRetDetail()，写入返回ATS的明细
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            txCode = "PY4001";
            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpNowStartRecord = 0;//总条数
            int intPageNumber = 1;//页码数 默认查询第一页
            int tmpNowReadedCount = 0;//已读条数

            boolean tmpQryNext = true;
            while (tmpQryNext && tmpRespCode.length() == 0) {//分页查询
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("input");
                xmlWriter.writeElementString("accountNo", p_req7516.actNum);
                xmlWriter.writeElementString("beginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpCalendarTo.getTime()));
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();
                String signXml = getDataSignData(xmlWriter);
                if (signnatrue(signXml) == true) {
                    xmlWriter.writeElementString("signData", signature);
                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));
                    XmlTextReader tmpBkReader;
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String returnCode = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retCode");
                            String returnMsg = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retMsg");
                            if (isActiveRetCode(returnCode)) {
                                int tmpTotalRocords = 0;//总条数
                                if (tmpBkReader.getFirstText("/HZBANKB2C/ebank/output/turnPageTotalNum") != null && tmpBkReader.getFirstText("/HZBANKB2C/ebank/output/turnPageTotalNum").trim().length() > 0) {
                                    tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/HZBANKB2C/ebank/output/turnPageTotalNum"));
                                }
                                int tmpEachPiCount = 0;
                                if (tmpTotalRocords > 0) {
                                    while (tmpBkReader.read("/HZBANKB2C/ebank/output/result/row")) {
                                        tmpEachPiCount++;
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("recAccount");
                                        tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("recAccountName");
                                        String debitAmount = tmpBkReader.readedXElement.getSingleText("debitAmount");//借方金额
                                        String loanAmount = tmpBkReader.readedXElement.getSingleText("loanAmount");//贷方金额
                                        BigDecimal debitAmt = StringHelper.hasAnyChar(debitAmount) ? new BigDecimal(debitAmount) : BigDecimal.ZERO ;
                                        BigDecimal loanAmt = StringHelper.hasAnyChar(loanAmount) ? new BigDecimal(loanAmount) : BigDecimal.ZERO;
                                        //冲正情况下存在，debitAmount为负金额，loanAmount为0的情况，调整方式采用loanAmount-debitAmount，如值为正数，则为收入，反之为支出，金额为做差后的结果取绝对值
                                        BigDecimal tranAmt = loanAmt.subtract(debitAmt);
                                        tmpRetDetail.cdFlag = tranAmt.compareTo(BigDecimal.ZERO) > 0 ? "2" : "1";
                                        tmpRetDetail.tranAmt = Format.DecimalAmtFormat.format(new BigDecimal(tranAmt.toPlainString().replace("-","")));
                                        /*tmpRetDetail.cdFlag = Double.parseDouble(debitAmount) > 0 ? "1" : "2";
                                        tmpRetDetail.tranAmt = Double.parseDouble(tmpBkReader.readedXElement.getSingleText("debitAmount")) > 0 ? debitAmount : loanAmount;*/
                                        tmpRetDetail.accBal = Format.DecimalAmtFormat.format(new BigDecimal(tmpBkReader.readedXElement.getSingleText("balance").trim()));//余额
                                        String tranDate = tmpBkReader.readedXElement.getSingleText("transferDate");//yyyy-MM-dd 交易时间  系统格式为yyyy-MM-dd hh:mm:ss
                                        String tranTime = tmpBkReader.readedXElement.getSingleText("transferTime");//hh:mm:ss
                                        tmpRetDetail.tranDate = tranDate;
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime;
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;////起息日没有返回就用交易日
                                        tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("payRem");
                                        tmpRetDetail.bnkSeqNo = tmpBkReader.readedXElement.getSingleText("serialNo");
                                        tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                        if (StringHelper.isNullOrEmpty(tmpRetDetail.actNum)) {
                                            tmpRetDetail.actNum = p_req7516.actNum;
                                        }
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                                tmpNowReadedCount += tmpEachPiCount;//总记录数
                                if (tmpNowReadedCount < tmpTotalRocords)//查询下一页
                                {
                                    intPageNumber = intPageNumber + 1;//页码加一 查询第二页
                                    tmpNowStartRecord = tmpNowReadedCount + 1;//记录已经查询的记录个数
                                } else if (tmpNowReadedCount == tmpTotalRocords)//本次分页查询完毕
                                {
                                    tmpQryNext = false;
                                    tmpNowStartRecord = 0;
                                    tmpNowReadedCount = 0;
                                    continue;
                                }
                            } else {
                                tmpQryNext = false;
                                tmpRespCode = "-1";
                                tmpRespInfo = returnMsg;
                                break;
                            }
                        } else {
                            tmpQryNext = false;
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpQryNext = false;
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                } else {
                    tmpQryNext = false;
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSign[1];
                    break;
                }
            }

        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
